package com.heima.user.filter;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义过滤器
 *  获取用户id，存入ThreadLocal中
 */
@Slf4j
@Order(1)
@WebFilter(filterName = "userFilter",urlPatterns = "/api/*")
public class UserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest)request;
        //从请求头获取用户id
        String userId = servletRequest.getHeader("userId");
        if(StringUtils.isNotBlank(userId) && !"0".equals(userId) ){
            log.info("自媒体用户id："+userId);
            //存入ThreadLocal中
            UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        }
        chain.doFilter(request, response);
    }
}
